import graphene
from flask import Flask
from flask_graphql import GraphQLView

class Person(graphene.ObjectType):
    name = graphene.String()
    age = graphene.Int()

users =[
    Person(name="sxt",age="18"),
    Person(name="Mr.Li",age= "20")
]

class UpdatePerson(graphene.Mutation):
    person = graphene.Field(Person)
    msg = graphene.String()
    class Arguments:
        name = graphene.String()
        age = graphene.Int()
    def mutate(self,info,name,age):
        for u in users:
            if u.name == name:
                u.age = age
                return UpdatePerson(person =u,msg ="success")
        return UpdatePerson(msg='fail')

class DeletePerson(graphene.Mutation):
    person = graphene.Field(Person)
    msg = graphene.String()
    class Arguments:
        name = graphene.String()
    def mutate(self,info,name):
        for u in users:
            if u.name == name:
                users.remove(u)
                return UpdatePerson(person =u,msg ="success")
        return UpdatePerson(msg='fail')

# Mutation
class Mutation(graphene.ObjectType):    # 映射对外使用字段
    update_person = UpdatePerson.Field()
    delete_person = DeletePerson.Field()

class Query(graphene.ObjectType):
    persons = graphene.List(Person)

    def resolve_persons(self,info):
        return users
if __name__ =='__main__':
    schema = graphene.Schema(query=Query,mutation=Mutation)
    app = Flask(__name__)
    app.add_url_rule('/graphql',view_func=GraphQLView.as_view('grapql',schema=schema, graphiql=True))
    app.run(debug=True)